package com.ContactsWitch.jackiez;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.ContactsWitch.jackiez.util.LogUtil; 
import com.ContactsWitch.jackiez.db.*;




public class contactswitch extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
	private DBOpenHelper mOpenHelper;
	public static final int DIALOG_UPLOAD_PROGRESS = 0;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 1;

	private ProgressDialog mProgressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn_export = (Button)findViewById(R.id.exportbutton);
        Button btn_upload = (Button)findViewById(R.id.uploadbutton);
        Button btn_download = (Button)findViewById(R.id.downloadbutton);
        Button btn_import = (Button)findViewById(R.id.importbutton);
        
        btn_export.setOnClickListener(this);
        btn_upload.setOnClickListener(this);
        btn_download.setOnClickListener(this);
        btn_import.setOnClickListener(this);
    }
    

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.exportbutton:
			exportcontacts();
			break;
		case R.id.uploadbutton:
			starttoupload();
			break;
		case R.id.downloadbutton:
			starttodownload();
			break;
		case R.id.importbutton:
			importcontacts();
			break;
			
		}
	}

	public void exportcontacts(){
        Button btn_export = (Button)findViewById(R.id.exportbutton);
		mOpenHelper = new DBOpenHelper(btn_export.getContext());
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();	 
        String sql_insert;
	      ContentResolver cr = getContentResolver();    
	      //取得电话本中开始一项的光标  
	      Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			while (cursor.moveToNext()) {
				ContactInfo cci = new ContactInfo();
				//取得联系人名字
				 int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); 
				 cci.contactName = cursor.getString(nameFieldColumnIndex);
				LogUtil.LogShow("[ContactListView]", cci.contactName, LogUtil.DEBUG);
				// 取得联系人ID  
			    int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));  
		        Cursor phone=cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?", new String[]{Integer.toString(id)}, null);//再类ContactsContract.CommonDataKinds.Phone中根据查询相应id联系人的所有电话；
				LogUtil.LogShow("[ContactListView]", Integer.toString(id), LogUtil.DEBUG);
				sql_insert = "INSERT INTO mycontacts(raw_contacts_id,my_mimetype,data) values ('"+Integer.toString(id)+"','1','"+cci.contactName+"');";
				LogUtil.LogShow("[ContactListView]", sql_insert, LogUtil.DEBUG);
		         try {
		             db.execSQL(sql_insert);
		             setTitle("insert records ok!");
		         } catch (SQLException e) {
		             Log.e("ERROR", e.toString());
		         }
				    // 取得电话号码(可能存在多个号码)  
				    while (phone.moveToNext())  
				    {  
				        String strPhoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
						LogUtil.LogShow("[ContactListView]", strPhoneNumber, LogUtil.DEBUG);
						sql_insert = "INSERT INTO mycontacts(raw_contacts_id,my_mimetype,data) values ('"+Integer.toString(id)+"','2','"+strPhoneNumber+"');";
				         try {
				             db.execSQL(sql_insert);
				             setTitle("insert records ok!");
				         } catch (SQLException e) {
				             Log.e("ERROR", e.toString());
				         }
						}
				    }  
				cursor.close();	         		
	}
	

    private void starttoupload(){
    	new UploadFileAsync().execute();

    }
    
    private void starttodownload(){
    	try{
    		File dir = new File("/data/data/com.ContactsWitch.jackiez/databases/");
    		dir.mkdir();
    	}
    	catch(Exception e){
			LogUtil.LogShow("[download]", "the folder already been or creating error!", LogUtil.DEBUG);

    	}
    	String url = "http://test.bjcargo.com/ContactsWitch510.txt";
    	new DownloadFileAsync().execute(url);

    }    
    
    private void importcontacts(){
        Button btn_import = (Button)findViewById(R.id.importbutton);
		mOpenHelper = new DBOpenHelper(btn_import.getContext());
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
	    //ContentResolver cr = getContentResolver();
        //String[] parms=new String[] {"1"};
    	ArrayList<ContentProviderOperation> ops;
    	int rawContactInsertIndex;
	    Cursor cursor1 = db.rawQuery("SELECT data,raw_contacts_id FROM mycontacts WHERE my_mimetype='1' ", null);
	    Cursor cursor2; 
		while (cursor1.moveToNext()) {
			ContactInfo cci = new ContactInfo();
			//取得联系人名字
			cci.contactName = cursor1.getString(0);
			cci.contactrawid = cursor1.getInt(1);
			LogUtil.LogShow("[Import]", cci.contactName, LogUtil.DEBUG);
	    	ops = new ArrayList();
	    	rawContactInsertIndex = ops.size(); 
	    	ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
	    			.withValue(RawContacts.ACCOUNT_TYPE,null)
	    			.withValue(RawContacts.ACCOUNT_NAME,null)
	    			.build());
	    	ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
	    			.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
	    			.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
	    			.withValue(StructuredName.DISPLAY_NAME, cci.contactName)
	    			.build());
			cursor2 = db.rawQuery("SELECT data FROM mycontacts WHERE my_mimetype='2' AND raw_contacts_id="+cci.contactrawid, null);
			while(cursor2.moveToNext()){
				cci.userNumber = cursor2.getString(0);
		    	ops.add(ContentProviderOperation.newInsert(
		    		    Data.CONTENT_URI)
		    		    .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
		    		    .withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
		    		    .withValue(Phone.NUMBER,cci.userNumber)
		    		    .withValue(Phone.TYPE, Phone.TYPE_MOBILE)
		    		    .build());
				LogUtil.LogShow("[Import]", cci.userNumber, LogUtil.DEBUG);
			}
			
	    	try {
				getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (OperationApplicationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 	
		}


    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_UPLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Uploading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    case DIALOG_DOWNLOAD_PROGRESS:
    mProgressDialog = new ProgressDialog(this);
    mProgressDialog.setMessage("Downloading file..");
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mProgressDialog.setCancelable(false);
    mProgressDialog.show();
    return mProgressDialog;
    default:
    return null;
    }
    }
    
	//The Uploading AsyncTask
	class UploadFileAsync extends AsyncTask< String, String, String> {
		
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_UPLOAD_PROGRESS);
	}
	
	@Override
	protected String doInBackground(String... aurl) {
    	FTPClient ftp = new FTPClient();
    	String server = "203.171.225.126";
    	String username="zhaojian";
    	String password="Huaren178";
    	String file="/data/data/com.ContactsWitch.jackiez/databases/ContactsWitch.db";
		try{
    		ftp.setDefaultTimeout(30000);
    		ftp.connect(server);
    		ftp.login(username,password);
    		ftp.setDefaultPort(21);
    		int reply = ftp.getReplyCode();
			LogUtil.LogShow("[upload]", Integer.toString(reply), LogUtil.DEBUG);

    		if(!FTPReply.isPositiveCompletion(reply)){
    			ftp.disconnect();
    			//showDialog("FTP Server connecting failed!!!");
    		}
    		else{
    			LogUtil.LogShow("[upload]", Integer.toString(reply), LogUtil.DEBUG);
				ftp.enterLocalPassiveMode();
				//ftp.setControlEncoding("gbk");
				ftp.setFileType(FTP.BINARY_FILE_TYPE);
				FileInputStream fis = new FileInputStream(new File(file));
				ftp.storeFile("ContactsWitch510.txt", fis);   				
				ftp.logout();
				//LogUtil.LogShow("[upload]", "12345", LogUtil.DEBUG);
    		}
    	}
		catch(Exception e){
			LogUtil.LogShow("[upload]", "Something Wrong!", LogUtil.DEBUG);
		}
    	finally
    	{
    		if(ftp.isConnected()){
    			try{
    				ftp.disconnect();
    			}
    			catch(Exception ioe){
    				LogUtil.LogShow("[upload]", "Something Wrong!", LogUtil.DEBUG);
    			}
    		}
    	}
		
		return null;

	}
	
	protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
	@Override
	protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_UPLOAD_PROGRESS);
		}
	}
	
	
	//The downloading Asynctask
	class DownloadFileAsync extends AsyncTask< String, String, String> {
		@Override
		protected void onPreExecute() {
		super.onPreExecute();
		showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

		 
		@Override
		protected String doInBackground(String... aurl) {
		int count;
		try {
		URL url = new URL(aurl[0]);
		URLConnection conexion = url.openConnection();
		conexion.connect();
		int lenghtOfFile = conexion.getContentLength();
		Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
		InputStream input = new BufferedInputStream(url.openStream());
		OutputStream output = new FileOutputStream("/data/data/com.ContactsWitch.jackiez/databases/ContactsWitch.db");
		byte data[] = new byte[1024];
		long total = 0;
		while ((count = input.read(data)) != -1) {
		total += count;
		publishProgress(""+(int)((total*100)/lenghtOfFile));
		output.write(data, 0, count);
		}
		output.flush();
		output.close();
		input.close();
		} catch (Exception e) {
		Log.e("error",e.getMessage().toString());
		System.out.println(e.getMessage().toString());
		}
		return null;
		}
		protected void onProgressUpdate(String... progress) {
		Log.d("ANDRO_ASYNC",progress[0]);
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
		}

		 
		@Override
		protected void onPostExecute(String unused) {
		dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
		}
		}
	
	
	
	}
